package com.lry.basic.juc;


import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/7/3
 */
public class TestThreadPool {

    public static void main(String[] args) {
//        private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
//        private static final int COUNT_BITS = Integer.SIZE - 3;
//        private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
//
//        // runState is stored in the high-order bits
//        private static final int RUNNING    = -1 << COUNT_BITS;
//        private static final int SHUTDOWN   =  0 << COUNT_BITS;
//        private static final int STOP       =  1 << COUNT_BITS;
//        private static final int TIDYING    =  2 << COUNT_BITS;
//        private static final int TERMINATED =  3 << COUNT_BITS;
//
//        // Packing and unpacking ctl
//        private static int runStateOf(int c)     { return c & ~CAPACITY; }
//        private static int workerCountOf(int c)  { return c & CAPACITY; }
//        private static int ctlOf(int rs, int wc) { return rs | wc; }

        ThreadFactory factory = new ThreadFactory() {
            AtomicInteger atomic = new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r,"MyThread--"+atomic.getAndIncrement());
                return thread;
            }
        };

        ThreadPoolExecutor exec = new ThreadPoolExecutor
                (105,
                1000,
                0,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(),
                factory,
                new ThreadPoolExecutor.AbortPolicy());


        for(int i=0;i<100;i++)
        exec.execute(()-> {
//            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        while(true){
            System.out.println(exec.getActiveCount());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }
}

//        Worker继承AQS，目的是想使用独占锁来表示线程是否正在执行任务，
//        Worker的线程获取了独占锁就说明它在执行任务，不能被中断。
//        从tryAcquire方法可以看出，它实现的是不可重入锁，
//        因为是否获得锁在这里表示一个状态，如果可以重入的话，
//        独占锁就失去了只表示一个状态的含义。在构造函数初始化时
//        ，Worker将state设置为-1，因为在tryAcquire中CAS操作compareAndSetState(0, 1)，
//        表示state在-1时不能被中断。在runWorker中将state设置为0.

